#region License

/*
  GShield - Game Shield
  Copyright (C) 2006-2007 WaveTech Digital Technologies, Inc.
                                http://www.wtdt.com

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#endregion License

#region Includes

using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using WaveTech.GShield.Engine.Managers;
using WaveTech.GShield.Engine.Systems;
using WaveTech.GShield.Model;

#endregion

namespace WaveTech.GShield.Watchdog
{
	public class Worker
	{
		private static bool Authroized = true;

		#region Constructor

		public Worker()
		{
			InitKillSignalWatcher();
		}

		#endregion Construtor

		#region Watchdog Worker

		public void WatchdogWorker()
		{
			while (Authroized)
			{
				if (DatabaseManager.Instance.GetServiceStatus() == false)
					DatabaseManager.Instance.StartService();

				if (ServiceManager.GetSentinelServiceStatus() == false)
					ServiceManager.StartSentinelService();

				Thread.Sleep(3600000);
			}
		}

		#endregion Watchdog Worker

		#region Init Kill Signal Watcher

		private void InitKillSignalWatcher()
		{
			Thread watcher = new Thread(KillSignalWatcher);
			watcher.Start();
		}

		#endregion Init Kill Signal Watcher

		#region Kill Signal Watcher

		private void KillSignalWatcher()
		{
			while (File.Exists(Application.StartupPath + "\\WatchdogKillSig") == false)
			{
				Thread.Sleep(30000);
			}

			Logging.Write("Watchdog Kill Signal Detected.", LogCategory.Watchdog, LogPriority.High, LogType.System);

			Authroized = false;

			File.Delete(Application.StartupPath + "\\WatchdogKillSig");
			Environment.Exit(1);
		}

		#endregion Kill Signal Watcher
	}
}